package com.ruoyi.hatha.controller;

import java.io.IOException;
import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.time.LocalDate;
import java.time.ZoneId;
import java.util.*;
import java.util.logging.Logger;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.alibaba.fastjson2.JSON;
import com.alibaba.fastjson2.JSONArray;
import com.alibaba.fastjson2.JSONObject;
import com.huifu.adapay.Adapay;
import com.huifu.adapay.core.AdapayCore;
import com.huifu.adapay.core.exception.BaseAdaPayException;
import com.huifu.adapay.core.util.AdapaySign;
import com.huifu.adapay.model.MerConfig;
import com.huifu.adapay.model.Payment;
import com.ruoyi.common.core.domain.entity.SysUser;
import com.ruoyi.common.utils.SecurityUtils;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.hatha.domain.*;
import com.ruoyi.hatha.service.*;
import com.ruoyi.system.service.ISysUserService;
import com.ruoyi.tools.OrderGen;
import com.ruoyi.tools.WeChatConstant;
import com.ruoyi.tools.WxPayTool;
import com.wechat.pay.java.service.payments.jsapi.model.Amount;
import com.wechat.pay.java.service.payments.jsapi.model.Payer;
import com.wechat.pay.java.service.payments.jsapi.model.PrepayRequest;
import com.wechat.pay.java.service.payments.jsapi.model.PrepayWithRequestPaymentResponse;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import com.ruoyi.common.annotation.Log;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.enums.BusinessType;
import com.ruoyi.common.utils.poi.ExcelUtil;
import com.ruoyi.common.core.page.TableDataInfo;

/**
 * 订单管理Controller
 * 
 * @author Dong
 * @date 2024-01-02
 */
@RestController
@RequestMapping("/hatha/order")
public class PKcOrderController extends BaseController
{

    private static  final Logger log = Logger.getLogger(PKcOrderController.class.getName());

    @Autowired
    private IPKcOrderService pKcOrderService;
    @Autowired
    private IPKechengService pKechengService;
    @Autowired
    private IPTaocanService ipTaocanService;
    @Autowired
    private IPCardsService pcardsService;
    @Autowired
    private ISysUserService sysUserService;
    @Autowired
    private IPPayUserService payUserService;
    @Autowired
    private IPMykcService mykcService;
    @Autowired
    private IPMytaocanService mytaocanService;
    @Autowired
    private IPMyvipService myvipService;
    @Autowired
    private IPYueService pYueService;

    /**
     * 查询订单管理列表
     */
    @PreAuthorize("@ss.hasPermi('hatha:order:list')")
    @GetMapping("/list")
    public TableDataInfo list(PKcOrder pKcOrder)
    {
        startPage();
        List<PKcOrder> list = pKcOrderService.selectPKcOrderList(pKcOrder);
        for(int i=0;i<list.size();i++){
            Long uid = list.get(i).getUid();
            SysUser su = sysUserService.selectUserById(uid);
            list.get(i).setSysUser(su);

            Integer type = list.get(i).getType();

            if(type==1){
                PKecheng kecheng = pKechengService.selectPKechengById(list.get(i).getKcid());
                list.get(i).setKecheng(kecheng);
            }

            if(type==2){
                PTaocan taocan = ipTaocanService.selectPTaocanById(list.get(i).getTcid());
                list.get(i).setTaocan(taocan);
            }

            if(type==3){
                PCards cards = pcardsService.selectPCardsById(list.get(i).getCcid());
                list.get(i).setCards(cards);
            }

        }
        return getDataTable(list);
    }

    /**
     * 导出订单管理列表
     */
    @PreAuthorize("@ss.hasPermi('hatha:order:export')")
    @Log(title = "订单管理", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    public void export(HttpServletResponse response, PKcOrder pKcOrder)
    {
        List<PKcOrder> list = pKcOrderService.selectPKcOrderList(pKcOrder);
        ExcelUtil<PKcOrder> util = new ExcelUtil<PKcOrder>(PKcOrder.class);
        util.exportExcel(response, list, "订单管理数据");
    }

    @GetMapping("/listall")
    public AjaxResult listall(PKcOrder pKcOrder)
    {
        pKcOrder.setUid(SecurityUtils.getUserId());
        List<PKcOrder> list = pKcOrderService.selectPKcOrderList(pKcOrder);
        return AjaxResult.success(list);
    }

    @GetMapping("/userInfo/{uid}")
    public AjaxResult userInfo(@PathVariable("uid") Long uid)
    {

        Map<String,Object> map = new HashMap<>();

        SysUser su = sysUserService.selectUserById(uid);
        map.put("userinfo",su);

        PMyvip pmv = new PMyvip();
        pmv.setUid(uid);
        List<PMyvip> lp = myvipService.selectPMyvipList(pmv);
        for(int i=0;i<lp.size();i++){
            Long cid = lp.get(i).getCardId();
            PCards pc = pcardsService.selectPCardsById(cid);
            lp.get(i).setCard(pc);
        }
        map.put("cards",lp);

        PMytaocan pmt = new PMytaocan();
        pmt.setUid(uid);
        List<PMytaocan> lt = mytaocanService.selectPMytaocanList(pmt);
        for(int i=0;i<lt.size();i++){
            Long tid = lt.get(i).getTcid();
            PTaocan pc = ipTaocanService.selectPTaocanById(tid);
            lt.get(i).setTaocan(pc);
        }
        map.put("taocan",lt);

        PMykc mkc = new PMykc();
        mkc.setUid(uid);
        List<PMykc> lpmkc = mykcService.selectPMykcList(mkc);
        for(int i=0;i<lpmkc.size();i++){
            Long kid = lpmkc.get(i).getKcid();
            PKecheng kec = pKechengService.selectPKechengById(kid);
            lpmkc.get(i).setKecheng(kec);
        }
        map.put("kecheng",lpmkc);

        return AjaxResult.success(map);
    }

    /**
     * 获取订单管理详细信息
     */
    @PreAuthorize("@ss.hasPermi('hatha:order:query')")
    @GetMapping(value = "/{id}")
    public AjaxResult getInfo(@PathVariable("id") Long id)
    {
        return success(pKcOrderService.selectPKcOrderById(id));
    }

    /**
     * 新增订单管理
     */
    @PreAuthorize("@ss.hasPermi('hatha:order:add')")
    @Log(title = "订单管理", businessType = BusinessType.INSERT)
    @PostMapping
    public AjaxResult add(@RequestBody PKcOrder pKcOrder)
    {
        return toAjax(pKcOrderService.insertPKcOrder(pKcOrder));
    }


    @GetMapping("/genOrder")
    public AjaxResult genOrder(PKcOrder pKcOrder) throws Exception {

        String ordernum = OrderGen.generateOrderNumber();
        pKcOrder.setOrdernum(ordernum);
        pKcOrder.setCreatetim(new Date());
        pKcOrder.setUid(SecurityUtils.getUserId());
        pKcOrder.setOpenid(SecurityUtils.getLoginUser().getUser().getOpenid());

        if(pKcOrder.getType()==1){//课程
            Long kid = pKcOrder.getKcid();
            PKecheng k = pKechengService.selectPKechengById(kid);
            BigDecimal result = k.getJiage().multiply(new BigDecimal("100"));
            pKcOrder.setJine(k.getJiage().toString());
            pKcOrder.setGdname(k.getName());
            pKcOrder.setMid(k.getMid());
        }
        if(pKcOrder.getType()==2){//套餐
            Long tid = pKcOrder.getTcid();
            PTaocan t = ipTaocanService.selectPTaocanById(tid);
            BigDecimal result = t.getJiage().multiply(new BigDecimal("100"));
            pKcOrder.setJine(t.getJiage().toString());
            if(t.getType()==2){
                pKcOrder.setCzje(t.getSjje());
            }
            pKcOrder.setGdname(t.getName());
            pKcOrder.setMid(t.getMdid());
        }
        if(pKcOrder.getType()==3){//会员
            Long cid = pKcOrder.getCcid();
            PCards pc = pcardsService.selectPCardsById(cid);
            BigDecimal result = pc.getJiage().multiply(new BigDecimal("100"));
            pKcOrder.setJine(pc.getJiage().toString());
            pKcOrder.setGdname(pc.getName()+pc.getYxq()+"天");
            pKcOrder.setMid(null);
        }

//        pKcOrderService.insertPKcOrder(pKcOrder);

        Map<String, Object> payInfo = getPayInfo(pKcOrder);

        if(payInfo!=null){
            return AjaxResult.success("ok",payInfo);
        }else{
            return AjaxResult.error("获取支付信息失败");
        }
    }

    private Map<String, Object> getPayInfo(PKcOrder pKcOrder) throws Exception {
        Adapay.debug = true;
        Adapay.prodMode = true;
        String apiKey = "api_live_dc9dd8df-b9a9-4d58-a7ba-974bf75ac8cb";
        String mockApiKey = "api_test_d1f93046-b897-42cc-b726-1f6220260a60";
        String rsaPrivateKey = "MIICdgIBADANBgkqhkiG9w0BAQEFAASCAmAwggJcAgEAAoGBAJFwVx0ZBLTG7JdsXAsJ5XCZ59seRGyEdz3LCOIjuf+V4CVVQgzNruMGkYD6dWd1PIo/XJZLrzyaKd9DqR+SvJjMvl1QVsm2KdAQkzmfDIEYlk+aKf2rhJwgwHCjCZw76ORjQoywjHYJXAv/+gkA/TsoJOhnkk6VeF6k/zrRooSbAgMBAAECgYAB4TDPCHa+G2ANaPIblmontWWAuHhr6p5b5xbbTVjnC7nU4bAz2CiteHVC9Hm195brtnvs2VePcfKelxJFfTEAx2m/I1G4cU1OUgaOKRwUL1IrTbTPdyuMosXG4X4FHsxnBF7sANOzt3Budgu/1Wc00dI6DsA/WrWPs/kFUNHFUQJBAPYrKpWQgqeF95OUKfJtdogscsj+gbkl/z+dgskD5t7SlCGE4C5LF7BcDkUAx8Uq4s8yaeYzFaUI53BuBSUr/9MCQQCXP09sO+wTP+rTLFdoPe6jC60ZrH12v2OofgJSpbZTQeRsrYq7xUjYgHmBe9w9BMCc8BzjNOBlIHSgP9Gt8rMZAkEA3q9b3WKVnp/Ev37Xl1NIV5UF3SbGCMwDo/ODvP3HmqgZklzWQ2pwqnwL+IXlMUpDVLXBMJnjqaBtZLpR8zdjOwJAa7n9QPMhP8i74jNoAmhyS5FqdqnkJytEuWMfFmzPg1egckPdV8a6DvLbGH33LULwShfAC5jC52SJjQZHu6TtKQJABlE+ui8xYjNygH2Z/c+pstyerFT1DRZnpGBt2kQ2BUqW3+G8UA0OBhKtko01j48KbkBpw6sdd2VmPcm8ArBCGg==";
        MerConfig merConfig = new MerConfig();
        merConfig.setApiKey(apiKey);
        merConfig.setApiMockKey(mockApiKey);
        merConfig.setRSAPrivateKey(rsaPrivateKey);
        Adapay.initWithMerConfig(merConfig);

        String appId = "app_cc612f06-2165-4e66-b6f6-5bb21975f0b8";

        Map<String, Object> paymentParams = new HashMap<String, Object>(10);
        Map<String,Object> deviceInfo = new HashMap<>();
        paymentParams.put("app_id", appId);
        paymentParams.put("order_no", pKcOrder.getOrdernum());
        paymentParams.put("pay_channel", "wx_lite");
        paymentParams.put("pay_amt", pKcOrder.getJine());
        paymentParams.put("goods_title", pKcOrder.getGdname());
        paymentParams.put("goods_desc", pKcOrder.getGdname());
//        paymentParams.put("div_members", "");
        paymentParams.put("open_id", pKcOrder.getOpenid());
        paymentParams.put("wx_app_id", "wxb9e738da2a0ed2c9");
        paymentParams.put("is_raw", "1");
        paymentParams.put("notify_url", "https://www.myhathayoga.cn/hatha/order/callback");

        if(pKcOrder.getType() == 3){

            PCards pc = pcardsService.selectPCardsById(pKcOrder.getCcid());

            //查询自己的上级
            Long user_id = SecurityUtils.getUserId();
//            Long user_id = 122L;

            SysUser user = sysUserService.selectUserById(user_id);
            Long puid = user.getPuid();
            SysUser vuser = sysUserService.selectUserById(puid);
            String pids = user.getPuids()+"";


            //查询上级和我的 会员类型是否一致
            PMyvip pv = new PMyvip();
            pv.setUid(puid);
            pv.setCardId(pKcOrder.getCcid());
            List<PMyvip> lvip = myvipService.selectPMyvipList(pv);

            if(puid!=null&&lvip.size()!=0&&"1".equals(pc.getOpenfx())){ //会员类型一致并且开启开关才会分佣

                //查询当前是20 还是 80 的比例
                PPayUser qpu = new PPayUser();
//                qpu.setUid(user_id);
                qpu.setVuid(puid);
                List<PPayUser> lpu = payUserService.selectPPayUserList(qpu);


                Integer num = lpu.size();

                Double rate = 0.2;

                if(num!=0){
                    if(isEven(num)){//如果当前是偶数，代表当前分账比例为20%  否则为80%
                        rate = 0.2;
                    }else{
                        rate = 0.8;
                    }
                }

                double jine = Double.parseDouble(pKcOrder.getJine());
                String a = String.format("%.2f", jine * rate);
                String b = String.format("%.2f", jine - Double.parseDouble(a));

                List<Map<String,Object>> fzfs = new ArrayList<>();
                Map<String,Object> fzf = new HashMap<>();
                Map<String,Object> fzf2 = new HashMap<>();

                /**推二返本 开始**/

                fzf.put("amount",a);
                fzf.put("fee_flag","Y");
                fzf.put("member_id",puid.toString());
                fzfs.add(fzf);
                /**推二返本 结束**/



                /**红包奖励 开始**/
                if(!"".equals(pids)){
                    String[] arrpids =  pids.split(",");
                    Integer pn =arrpids.length;
                    if(pn>=2&&!isEven(num)){//大于等于2 并且当前交易是奇数时 才会产生分红
                        Double r = 0.2;
                        String c = String.format("%.2f", jine * r);
                        if(pn==2){//全给A
                            fzf2.put("amount",c);
                            fzf2.put("fee_flag","N");
                            fzf2.put("member_id",arrpids[0]);
                            fzfs.add(fzf2);
                        }else if(pn==3){//分给A 和 B
                            List<Double> splitValues = splitRandomly(jine*0.2, 2);
                            fzf2.put("amount",String.format("%.2f", splitValues.get(0)));
                            fzf2.put("fee_flag","N");
                            fzf2.put("member_id",arrpids[0]);
                            fzfs.add(fzf2);
                            Map<String,Object> fzf3 = new HashMap<>();
                            fzf3.put("amount",String.format("%.2f", splitValues.get(1)));
                            fzf3.put("fee_flag","N");
                            fzf3.put("member_id",arrpids[1]);
                            fzfs.add(fzf3);
                        }else if(pn>3){
                            List<Double> splitValues = splitRandomly(jine*0.2, 3);
                            String u1 = arrpids[pn-4];//A
                            String u2 = arrpids[pn-3];//B
                            String u3 = arrpids[pn-2];//C
                            String[] npids = {u1,u2,u3};

                            for(int i=0;i<3;i++){
                                Map<String,Object> fzfmap = new HashMap<>();
                                fzfmap.put("amount",String.format("%.2f", splitValues.get(i)));
                                fzfmap.put("fee_flag","N");
                                fzfmap.put("member_id",npids[i]);
                                fzfs.add(fzfmap);
                            }
                        }
                    }else{
                        fzf2.put("amount",b);
                        fzf2.put("fee_flag","N");
                        fzf2.put("member_id","0");
                        fzfs.add(fzf2);
                    }
                }else{
                    fzf2.put("amount",b);
                    fzf2.put("fee_flag","N");
                    fzf2.put("member_id","0");
                    fzfs.add(fzf2);
                }
                /**红包奖励 结束**/
                System.out.println("↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓分账数据↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓");
                System.out.println(JSON.toJSON(fzfs));
                paymentParams.put("div_members", JSON.toJSON(fzfs));
            }

        }
        JSONObject expend = new JSONObject();
        expend.put("open_id",pKcOrder.getOpenid());
        paymentParams.put("expend",expend);
        Map<String, Object> payment = Payment.create(paymentParams);

        if("succeeded".equals(payment.get("status"))){
            pKcOrder.setPaymentId(payment.get("id").toString());
            pKcOrderService.insertPKcOrder(pKcOrder);
        }else{
            return null;
        }

        return payment;
    }


    public static List<Double> splitRandomly(double originalValue, int numParts) {
        List<Double> parts = new ArrayList<>();
        Random random = new Random();

        // 生成初始的随机数，总和可能不等于originalValue
        for (int i = 0; i < numParts - 1; i++) {
            double part = originalValue * random.nextDouble(); // 生成一个0到originalValue之间的随机数
            if(part<0.01)
                part = 0.01;
            parts.add(part);
            originalValue -= part; // 从原始值中减去已分配的部分
        }
        // 最后一部分直接是剩余的原始值，确保总和正确
        parts.add(originalValue);

        return parts;
    }


    public static boolean isEven(int num) {
        return num % 2 == 0;
    }

    @GetMapping("/getOrderStatus")
    public AjaxResult getOrderStatus(String payment_id) throws Exception {
        PKcOrder pko = new PKcOrder();
        pko.setPaymentId(payment_id);


        for(int i=0;i<10;i++){
            List<PKcOrder> lpko = pKcOrderService.selectPKcOrderList(pko);
            PKcOrder pkoi = lpko.get(0);

            if(pkoi.getIspay()==1){
                return AjaxResult.success("支付成功");
            }
            Thread.sleep(1000);
        }
        return AjaxResult.error("未查询到结果");
    }
    @GetMapping("/queryPayOrder")
    @Transactional
    public AjaxResult queryPayOrder(String payment_id) throws Exception {
        Adapay.debug = true;
        Adapay.prodMode = true;
        String apiKey = "api_live_dc9dd8df-b9a9-4d58-a7ba-974bf75ac8cb";
        String mockApiKey = "api_test_d1f93046-b897-42cc-b726-1f6220260a60";
        String rsaPrivateKey = "MIICdgIBADANBgkqhkiG9w0BAQEFAASCAmAwggJcAgEAAoGBAJFwVx0ZBLTG7JdsXAsJ5XCZ59seRGyEdz3LCOIjuf+V4CVVQgzNruMGkYD6dWd1PIo/XJZLrzyaKd9DqR+SvJjMvl1QVsm2KdAQkzmfDIEYlk+aKf2rhJwgwHCjCZw76ORjQoywjHYJXAv/+gkA/TsoJOhnkk6VeF6k/zrRooSbAgMBAAECgYAB4TDPCHa+G2ANaPIblmontWWAuHhr6p5b5xbbTVjnC7nU4bAz2CiteHVC9Hm195brtnvs2VePcfKelxJFfTEAx2m/I1G4cU1OUgaOKRwUL1IrTbTPdyuMosXG4X4FHsxnBF7sANOzt3Budgu/1Wc00dI6DsA/WrWPs/kFUNHFUQJBAPYrKpWQgqeF95OUKfJtdogscsj+gbkl/z+dgskD5t7SlCGE4C5LF7BcDkUAx8Uq4s8yaeYzFaUI53BuBSUr/9MCQQCXP09sO+wTP+rTLFdoPe6jC60ZrH12v2OofgJSpbZTQeRsrYq7xUjYgHmBe9w9BMCc8BzjNOBlIHSgP9Gt8rMZAkEA3q9b3WKVnp/Ev37Xl1NIV5UF3SbGCMwDo/ODvP3HmqgZklzWQ2pwqnwL+IXlMUpDVLXBMJnjqaBtZLpR8zdjOwJAa7n9QPMhP8i74jNoAmhyS5FqdqnkJytEuWMfFmzPg1egckPdV8a6DvLbGH33LULwShfAC5jC52SJjQZHu6TtKQJABlE+ui8xYjNygH2Z/c+pstyerFT1DRZnpGBt2kQ2BUqW3+G8UA0OBhKtko01j48KbkBpw6sdd2VmPcm8ArBCGg==";
        MerConfig merConfig = new MerConfig();
        merConfig.setApiKey(apiKey);
        merConfig.setApiMockKey(mockApiKey);
        merConfig.setRSAPrivateKey(rsaPrivateKey);
        Adapay.initWithMerConfig(merConfig);

//        String appId = "app_cc612f06-2165-4e66-b6f6-5bb21975f0b8";

        Map<String, Object> response = Payment.query(payment_id);

        System.out.println(response);

        if("succeeded".equals(response.get("status"))){
            //更新订单状态
            PKcOrder pko = new PKcOrder();
            pko.setPaymentId(payment_id);
            List<PKcOrder> lpko = pKcOrderService.selectPKcOrderList(pko);
            PKcOrder pkoi = lpko.get(0);

            pkoi.setIspay(1);
            pkoi.setState(1);
            pKcOrderService.updatePKcOrder(pkoi);

            Integer ot = pkoi.getType();
            //添加到我的课程 、 套餐 、 会员卡
            if(ot==1){//添加到我的课程
                PMykc pMykc = new PMykc();
                pMykc.setKcid(pkoi.getKcid());
                pMykc.setIsused(0);
                pMykc.setOid(pkoi.getId());
                pMykc.setUid(pkoi.getUid());
                pMykc.setCreateTime(new Date());
                mykcService.insertPMykc(pMykc);
            }else if(ot==2){//添加到我的套餐

                Long tcid = pkoi.getTcid();

                PTaocan ptc = ipTaocanService.selectPTaocanById(tcid);
                if(ptc.getType()==1){//添加课程到我的课程
                    String[] kcs = ptc.getKcids().split(",");
                    for(int i=0;i<kcs.length;i++){
                        PMykc pMykc = new PMykc();
                        pMykc.setKcid(Long.valueOf(kcs[i]));
                        pMykc.setIsused(0);
                        pMykc.setOid(pkoi.getId());
                        pMykc.setUid(pkoi.getUid());
                        pMykc.setCreateTime(new Date());
                        mykcService.insertPMykc(pMykc);
                    }
                }else if(ptc.getType()==2){//充值
                    PYue pYue = new PYue();
                    pYue.setUid(pkoi.getUid());
                    pYue.setNum(Integer.valueOf(ptc.getSjje()));
                    pYue.setCreateUser(SecurityUtils.getUserId());
                    pYue.setCreateTime(new Date());
                    pYue.setType(1);//充值
                    pYueService.insertPYue(pYue);
                }

                PMytaocan pmt = new PMytaocan();
                pmt.setIsused(0);
                pmt.setTcid(pkoi.getTcid());
                pmt.setOrderId(pkoi.getId());
                pmt.setUid(pkoi.getUid());
                pmt.setCreateTime(new Date());
                mytaocanService.insertPMytaocan(pmt);
            }else if(ot==3){//会员卡开卡续期
                PMyvip pv = new PMyvip();
                pv.setUid(SecurityUtils.getUserId());
                pv.setCardId(pkoi.getCcid());//同一类型会员
                List<PMyvip> lpmv = myvipService.selectPMyvipList(pv);

                if(lpmv.size()==0){//新开卡
                    PMyvip npv = new PMyvip();
                    npv.setUid(SecurityUtils.getUserId());
                    npv.setCardId(pkoi.getCcid());
                    npv.setOrderId(pkoi.getId());

                    //查询卡券
                    PCards card = pcardsService.selectPCardsById(pkoi.getCcid());
                    Integer yxq = card.getYxq();
                    Calendar calendar = Calendar.getInstance();
                    calendar.add(Calendar.DAY_OF_MONTH, yxq);
                    Date dateInFuture = calendar.getTime();
                    npv.setEndTime(dateInFuture);
                    npv.setCreateTime(new Date());
                    myvipService.insertPMyvip(npv);
                }else{
                    PMyvip npv = lpmv.get(0);
                    Date end = npv.getEndTime();

                    //查询卡券
                    PCards card = pcardsService.selectPCardsById(pkoi.getCcid());
                    Integer yxq = card.getYxq();

                    Calendar calendar = Calendar.getInstance();
                    calendar.setTime(end);
                    calendar.add(Calendar.DAY_OF_MONTH, yxq);

                    Date futureDate = calendar.getTime();
                    npv.setEndTime(futureDate);
                    myvipService.updatePMyvip(npv);
                }

                //向邀请表增加新数据

                SysUser user = sysUserService.selectUserById(SecurityUtils.getUserId());
                if(user.getPuid()!=null && ot == 3){
                    Long uid = user.getUserId();
                    Long vuid = user.getPuid();
                    PPayUser pu = new PPayUser();
                    pu.setUid(uid);
                    pu.setVuid(vuid);
                    payUserService.insertPPayUser(pu);
                }

            }
        }

        return AjaxResult.success(response);

    }

    @PostMapping("/callback")
    @Transactional
    public AjaxResult callback(HttpServletRequest request) {
        try {
            //验签请参data
            String data = request.getParameter("data");
            System.out.println("data========="+data);
            //验签请参sign
            String sign = request.getParameter("sign");
            System.out.println("sign========="+sign);
            String type = request.getParameter("type");
            System.out.println("type========="+type);
            //验签标记
            boolean checkSign;
            //验签请参publicKey
            String publicKey = AdapayCore.PUBLIC_KEY;
            log.info("验签请参：data={}sign={}");
            //验签
            checkSign = AdapaySign.verifySign(data, sign, publicKey);
            if(checkSign){
                //{"app_id":"app_cc612f06-2165-4e66-b6f6-5bb21975f0b8","business_mode":"00","created_time":"20240513090024","description":"","end_time":"20240513090035","expend":{"bank_type":"OTHERS","cashPayAmt":"0.01","open_id":"o8jhotzqxVOgWERZFcK__N7tI6n0","sub_open_id":"o3FfG64CkA8fk0xi6EcEMe5dAKFg"},"fee_amt":"0.00","id":"002212024051309002410635897373209214976","order_no":"20240513090027104281","out_trans_id":"4200002228202405132187508189","party_order_id":"02212405133242432713163","pay_amt":"0.01","pay_channel":"wx_lite","real_amt":"0.01","share_eq":"Y","status":"succeeded","wx_user_id":""}

                if("payment.succeeded".equals(type)){//支付成功
                    JSONObject pinfo = JSON.parseObject(data);
                    String payment_id = pinfo.getString("id");
                    //更新订单状态
                    PKcOrder pko = new PKcOrder();
                    pko.setPaymentId(payment_id);
                    List<PKcOrder> lpko = pKcOrderService.selectPKcOrderList(pko);
                    PKcOrder pkoi = lpko.get(0);

                    String pt = pinfo.getString("end_time");
                    SimpleDateFormat formatter = new SimpleDateFormat("yyyyMMddHHmmss");

                    pkoi.setIspay(1);
                    pkoi.setState(1);
                    pkoi.setWxorder(pinfo.getString("out_trans_id"));
                    pkoi.setPaytime(formatter.parse(pt));
                    pKcOrderService.updatePKcOrder(pkoi);

                    Integer ot = pkoi.getType();
                    //添加到我的课程 、 套餐 、 会员卡
                    if(ot==1){//添加到我的课程
                        PMykc pMykc = new PMykc();
                        pMykc.setKcid(pkoi.getKcid());
                        pMykc.setIsused(0);
                        pMykc.setOid(pkoi.getId());
                        pMykc.setUid(pkoi.getUid());
                        pMykc.setCreateTime(new Date());
                        mykcService.insertPMykc(pMykc);
                        pkoi.setState(1);
                        pKcOrderService.updatePKcOrder(pkoi);
                    }else if(ot==2){//添加到我的套餐

                        Long tcid = pkoi.getTcid();

                        PTaocan ptc = ipTaocanService.selectPTaocanById(tcid);
                        if(ptc.getType()==1){//添加课程到我的课程
                            String[] kcs = ptc.getKcids().split(",");
                            for(int i=0;i<kcs.length;i++){
                                PMykc pMykc = new PMykc();
                                pMykc.setKcid(Long.valueOf(kcs[i]));
                                pMykc.setIsused(0);
                                pMykc.setOid(pkoi.getId());
                                pMykc.setUid(pkoi.getUid());
                                pMykc.setCreateTime(new Date());
                                mykcService.insertPMykc(pMykc);
                            }
                        }else if(ptc.getType()==2){//充值
                            PYue pYue = new PYue();
                            pYue.setUid(pkoi.getUid());
                            pYue.setNum(Integer.valueOf(ptc.getSjje()));
                            pYue.setCreateUser(pkoi.getUid());
                            pYue.setCreateTime(new Date());
                            pYue.setType(1);//充值
                            pYueService.insertPYue(pYue);
                        }

                        PMytaocan pmt = new PMytaocan();
                        pmt.setIsused(0);
                        pmt.setTcid(pkoi.getTcid());
                        pmt.setOrderId(pkoi.getId());
                        pmt.setUid(pkoi.getUid());
                        pmt.setCreateTime(new Date());
                        mytaocanService.insertPMytaocan(pmt);

                        pkoi.setState(2);
                        pKcOrderService.updatePKcOrder(pkoi);

                    }else if(ot==3){//会员卡开卡续期
                        PMyvip pv = new PMyvip();
                        pv.setUid(pkoi.getUid());
                        pv.setCardId(pkoi.getCcid());//同一类型会员
                        List<PMyvip> lpmv = myvipService.selectPMyvipList(pv);
                        PCards card = pcardsService.selectPCardsById(pkoi.getCcid());
                        if(lpmv.size()==0){//新开卡
                            PMyvip npv = new PMyvip();
                            npv.setUid(pkoi.getUid());
                            npv.setCardId(pkoi.getCcid());
                            npv.setOrderId(pkoi.getId());

                            Integer yxq = card.getYxq();
                            Calendar calendar = Calendar.getInstance();
                            calendar.add(Calendar.DAY_OF_MONTH, yxq);
                            Date dateInFuture = calendar.getTime();
                            npv.setEndTime(dateInFuture);
                            npv.setCreateTime(new Date());
                            npv.setType(card.getType());
                            npv.setSycs(card.getCs());
                            npv.setFid(card.getFid());
                            myvipService.insertPMyvip(npv);
                        }else{
                            PMyvip npv = lpmv.get(0);

                            Date end = npv.getEndTime();
                            Integer yxq = card.getYxq();
                            Calendar calendar = Calendar.getInstance();
                            calendar.setTime(end);
                            calendar.add(Calendar.DAY_OF_MONTH, yxq);
                            Date futureDate = calendar.getTime();
                            npv.setEndTime(futureDate);

                            if("4".equals(npv.getType())){
                                npv.setSycs(npv.getSycs()+card.getCs());
                            }

                            myvipService.updatePMyvip(npv);
                        }

                        pkoi.setState(2);
                        pKcOrderService.updatePKcOrder(pkoi);

                        //向邀请表增加新数据
                        if("1".equals(card.getOpenfx())){
                            SysUser user = sysUserService.selectUserById(pkoi.getUid());
                            if(user.getPuid()!=null && ot == 3){
                                Long uid = user.getUserId();
                                Long vuid = user.getPuid();
                                PPayUser pu = new PPayUser();
                                pu.setUid(uid);
                                pu.setVuid(vuid);
                                payUserService.insertPPayUser(pu);
                            }
                        }
                    }
                }
                //验签成功逻辑
                System.out.println("成功返回数据data:"+data);
            }else {
                //验签失败逻辑
                return AjaxResult.error("验签失败");
            }
        }catch (Exception e){
            log.info("异步回调开始，参数，request={}");
            return AjaxResult.error("消息失败");
        }
        return AjaxResult.success();
    }


    /**
     * 修改订单管理
     */
    @PreAuthorize("@ss.hasPermi('hatha:order:edit')")
    @Log(title = "订单管理", businessType = BusinessType.UPDATE)
    @PutMapping
    public AjaxResult edit(@RequestBody PKcOrder pKcOrder)
    {
        return toAjax(pKcOrderService.updatePKcOrder(pKcOrder));
    }

    /**
     * 删除订单管理
     */
    @PreAuthorize("@ss.hasPermi('hatha:order:remove')")
    @Log(title = "订单管理", businessType = BusinessType.DELETE)
	@DeleteMapping("/{ids}")
    public AjaxResult remove(@PathVariable Long[] ids)
    {
        return toAjax(pKcOrderService.deletePKcOrderByIds(ids));
    }
}
